package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Request.FindProductStoreReq;
import com.ydkj.a37e_mall.Classes.Model.Response.GetShopListResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.Rsa;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by Administrator on 2017/2/16.
 * 配送方式
 */

public class DistributionMode extends BaseActivity implements View.OnClickListener {
    private Activity mActivity;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private MyApplication myApplication;
    private RelativeLayout rly_express;
    private ImageView img_distribution_mode_thumb, img_back, img_distribution_mode_select;
    private TextView tv_distribution_mode_describe, tv_distribution_mode_price, tv_distribution_mode_color, tv_distribution_mode_type_content, tv_distribution_mode_num;
    private PullToRefreshListView lv_distribution_mode;
    private DistributionModeAdapter distributionModeAdapter;

    private List<GetShopListResp.ResultEntity.DataEntity> shopDataEntityList;
    public static final int LOAD = 0;// 加载
    public static final int REFRESH = 1;// 刷新
    public static final int MORE = 2;// 更多
    public static String secret;
    private String product_id;
    private String page;
    String index;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.distribution_mode);
        mActivity = this;
        init();
    }

    private void init() {
        sharedPreferencesUtil=SharedPreferencesUtil.getInstance(mActivity);
        myApplication=MyApplication.getInstance();
        rly_express= (RelativeLayout) mActivity.findViewById(R.id.rly_express);
        img_back = (ImageView) mActivity.findViewById(R.id.img_back);
        img_distribution_mode_thumb = (ImageView) mActivity.findViewById(R.id.img_distribution_mode_thumb);
        img_distribution_mode_select = (ImageView) mActivity.findViewById(R.id.img_distribution_mode_select);

        tv_distribution_mode_describe = (TextView) mActivity.findViewById(R.id.tv_distribution_mode_describe);
        tv_distribution_mode_price = (TextView) mActivity.findViewById(R.id.tv_distribution_mode_price);
        tv_distribution_mode_color = (TextView) mActivity.findViewById(R.id.tv_distribution_mode_color);
        tv_distribution_mode_type_content = (TextView) mActivity.findViewById(R.id.tv_distribution_mode_type_content);
        tv_distribution_mode_num = (TextView) mActivity.findViewById(R.id.tv_distribution_mode_num);

        if (this.getIntent().getExtras()!=null){
            product_id=this.getIntent().getExtras().getString("product_id");
            index=this.getIntent().getExtras().getString("position");
        }

        Log.e("url","product_id==="+product_id+" index=="+index);
        shopDataEntityList=new ArrayList<>();

        GetStoreList(LOAD);

        lv_distribution_mode = (PullToRefreshListView) mActivity.findViewById(R.id.lv_distribution_mode);
        distributionModeAdapter = new DistributionModeAdapter(shopDataEntityList);
        lv_distribution_mode.setAdapter(distributionModeAdapter);


        img_back.setOnClickListener(this);
        rly_express.setOnClickListener(this);
        img_distribution_mode_select.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.img_distribution_mode_select:
                break;
            case R.id.rly_express://三七快递
                Intent intent = new Intent(mActivity, ConfirmationOrder.class);
                intent.putExtra("delivery_type", "1");
                intent.putExtra("name","三七快递");
                intent.putExtra("store_id","0");
                intent.putExtra("position",index);
                setResult(Activity.RESULT_OK, intent);
                finish();
                break;
        }
    }

    private class DistributionModeAdapter extends BaseAdapter {
        private List<GetShopListResp.ResultEntity.DataEntity> list;

        private DistributionModeAdapter(List<GetShopListResp.ResultEntity.DataEntity> info) {
            this.list = info;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public GetShopListResp.ResultEntity.DataEntity getItem(int pisotion) {
            return list.get(pisotion);
        }

        @Override
        public long getItemId(int pisotion) {
            return pisotion;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup viewGroup) {
            ViewHolder vh = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.distribution_mode_list, null);
                vh = new ViewHolder();
                vh.tv_distribution_list_name = (TextView) convertView.findViewById(R.id.tv_distribution_list_name);
                vh.tv_distribution_list_num = (TextView) convertView.findViewById(R.id.tv_distribution_list_num);
                vh.tv_distribution_list_title = (TextView) convertView.findViewById(R.id.tv_distribution_list_title);
                vh.img_distribution_list_select = (ImageView) convertView.findViewById(R.id.img_distribution_list_select);

            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            convertView.setTag(vh);
            convertView.setClickable(true);

            vh.tv_distribution_list_name.setText(getItem(position).getName());
//            vh.tv_distribution_list_num.setText(getItem(position).getDistance());

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mActivity, ConfirmationOrder.class);
                    intent.putExtra("delivery_type", "2");
                    intent.putExtra("store_id",getItem(position).getId()+"");
                    intent.putExtra("name",getItem(position).getName());
                    intent.putExtra("position",index);
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }
            });
            return convertView;
        }

        private class ViewHolder {
            private TextView tv_distribution_list_name, tv_distribution_list_num, tv_distribution_list_title;
            private ImageView img_distribution_list_select;
        }
    }

    /** 获取门店 */
    private void GetStoreList(final int type){
        CustomProgressDialog.createDialog(mActivity).show();
        FindProductStoreReq req = new FindProductStoreReq();

        if (type == LOAD || type == REFRESH) {
            page = "1";
        } else {
            page = (shopDataEntityList.size() / 10 + 1) + "";
        }
        //uuid,type,product_id,lng,lat,page,page_size;
        if (myApplication.getDataEntity().getUuid() != null) {
            req.setUuid(myApplication.getDataEntity().getUuid());
        }
        req.setType("1");

        req.setProduct_id(product_id);
        if (sharedPreferencesUtil.getJingdu().equals("0") || sharedPreferencesUtil.getWeidu().equals("0")) {
            req.setLat("0");
            req.setLng("0");
        } else {
            req.setLat(sharedPreferencesUtil.getWeidu());
            req.setLng(sharedPreferencesUtil.getJingdu());
//            req.setLat("24.49358");
//            req.setLng("118.191569");
        }
        req.setPage(page);
        req.setPage_size("10");

        try {
            String source = req.getString();
            Log.e("url", "source==" + source);
            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(source);
        } catch (Exception e) {
            e.printStackTrace();
        }


        RequestParams params = new RequestParams();

        params.put("secret", secret);
        Async_http_get.get(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                lv_distribution_mode.onRefreshComplete();
                Log.e("url", "门店自提的json==" + response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
                    GetShopListResp resp = GsonImpl.get().toObject(response.toString(), GetShopListResp.class);
                    if (type == LOAD || type == REFRESH) {
                        shopDataEntityList.clear();
                        shopDataEntityList.addAll(resp.getResult().getData());
                    } else {
                        shopDataEntityList.addAll(resp.getResult().getData());
                    }
                    if (shopDataEntityList.size() % 10 > 0) {
                        lv_distribution_mode.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                    } else {
                        lv_distribution_mode.setMode(PullToRefreshBase.Mode.BOTH);
                    }
                    distributionModeAdapter.notifyDataSetChanged();
                } else if (errno.equals("003")) {
                    CommonUtil.showToast(mActivity, errmsg);
                    shopDataEntityList.clear();
                    distributionModeAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
                lv_distribution_mode.onRefreshComplete();
            }
        });
    }
}
